// var config = require('../config/'); 
var then = require('thenjs');
var gm        = require('gm');
var webdriverio = require('webdriverio');
var client = {};
var urllib = require('urllib');
var config = require('../config');
var options = config.options;
var fs        = require('fs');
var tesseract = require('node-tesseract');
var urlCache = {};
// var Cache = require('jsoncache');
// var cache = new Cache({ dir: './cache', life: 60*60, mode: 'json' });
// var cacheFile = './cache/022b150ae5b6cbed66ae1201494bd24e';
var redis = require('../libs/redis');
var crypto = require('crypto');
var Actions = {
    init: function(){
        Actions.checkCache();
        then(function (defer) {
            redis.get('key_cookie',defer);
        }).then(function (defer,cookieStr) {
            // console.info("cookieStr",cookieStr);
            if(cookieStr){
                Actions.startIntervalTask(cookieStr);
            }else{
                Actions.openWindow();
            }
        })

        // clearInterval(Actions.startGetDataTimeOut);
    },
    checkCache: function(){
        try{
            var content = fs.readFileSync(cacheFile,'utf-8');
            if(!content){
                fs.unlink(cacheFile);
            }
        }catch(e){

        }
    },
    openWindow: function(){
        try{
        client.close();
            client.end();
        }catch(e){}
        console.info('openWindow');
        client = webdriverio
        .remote(options)
        .init(function(err,doc){
            console.info(err);
            console.info(doc);
        })
        .windowHandleSize({width: 800, height: 600})
        .url('http://tongji.baidu.com/web/welcome/login')
        .getTitle().then(function(title) {
            console.log('Title was: ' + title);
            console.info('click');
            client.click('.login-trigger .dazzle-button-text')
            Actions.fillIn();
        })
    },
    fillIn: function(){
        setTimeout(function(){
            client
            .setValue('#UserName', 'aiskater')
            .setValue('#Password', 'dangtuo2008')
            .getTitle().then(function(title) {
                Actions.getCASCode();
            })
        },2000)
    },
    callback: function(err,code){
        console.info('code',code);
        if(code.length != 4||!/[0-9A-Za-z]/.test(code)){
            Actions.getCASCode();
        }else{
            Actions.login(code);
        }
    },
    over: function(){
        client.end();
    },
	/*
	 * 
	*/
	login : function (code) {
        client
        .setValue('#Valicode', code)
        .click('.login-btn')
        .waitForExist('#ErrorTip',10000).then(function(isVisible) {
            if(isVisible){
                console.log('login error,ErrorTip isVisible:',isVisible); // outputs: false
                Actions.fillIn();
            }
            // clearTimeout(Actions.successTimeOut);
        })
        client.waitForExist('#event-monitor-help-center',10000).then(function(isVisible) {
            console.info('#event-monitor-help-center',isVisible)
            if(!isVisible) return;
            console.log('login success'); // outputs: false
            client.getCookie().then(function(cookies) {
                client.close();
                client.end();
                var cookieStr = Actions.getCookieStr(cookies)
                Actions.startIntervalTask(cookieStr);
            });
        })
        // Actions.successTimeOut = setTimeout(function(){
        // },12000)
    },
    startIntervalTask: function(cookieStr){
        clearInterval(Actions.startGetDataTimeOut);
        Actions.startGetDataTimeOut = setInterval(function(){
            Actions.startGetData(cookieStr);
        },10000)
    },
    getCookieStr: function(cookies){
        if(typeof cookies != 'object') return cookies;
        var cookAry=[];
        for (var i = 0; i < cookies.length; i++) {
            var item = cookies[i];
            cookAry.push(item['name']+'='+item['value']);
        };
        return cookAry.join('; ');
    },
    startGetData: function(cookies){
        var cookieStr = Actions.getCookieStr(cookies)
        if(cookies)redis.set('key_cookie',cookieStr,function(err,doc){
            // console.info("startGetData error",err);
        });
        var url = 'http://tongji.baidu.com/web/7441284/ajax/post';
        var options = {
            method: 'POST',
            timeout: 10*1000,
            headers: {
                'Cookie': cookieStr,
                'Content-Type': 'application/x-www-form-urlencoded',
                'Referer': 'http://tongji.baidu.com/web/7441284/trend/latest?siteId=6790068',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0',
                'X-Requested-With': 'XMLHttpRequest',
                'Connection': 'keep-alive',
            },
            data: {
                indicators: 'area,start_time,source,access_page,ip,visitorId,visit_time,visit_pages',
                method: 'trend/latest/a',
                offset: 0,
                order: 'start_time,desc',
                queryId: '',
                reportId: 4,
                siteId: '6570934',
                // 来源百度
                // source: 'search,1',
            }
        }
        urllib.request(url, options, function(err, data, res){
            if (err) {
                console.info(err);
                return;
                // throw err; // you need to handle error 
            }
            // data is Buffer instance 
            var str = data.toString();
            if(!str){
                fs.unlink(cacheFile);
                Actions.init(); 
                return
            }
            // console.info("~~~~~~~~~~~~~~~str",str);
            var data = JSON.parse(str)
            try{                
                if(!data['data'])return;
                var items = data['data']['items'];
                if(!items)return;
                items = items[0];
            }catch(e){
                console.info('ERROR:',e);
                items = [];
            }
            console.info('get Data Success:' + new Date().getTime());
            Actions.sendItems(items);
        });
    },
/*
{ fromType: '百度(搜索词:牛商网)',
  url: 'http://www.baidu.com/link?url=D5YKBoLiNDtOC0-j3OKfGI3eCEtQjSx0dFyBIObs4FS&wd=%E7%89%9B%E5%95%86%E7%BD%91&eqid=956fbfa6000063e10000000257433580' }
*/ 
    sendItems: function(items){
        // console.info('items',JSON.stringify(items));
        for(var i =0;i<items.length;i++){
            try{
                var item = items[i];
                var md5 = crypto.createHash('md5');
                var md5Item = md5.update(JSON.stringify(item)).digest('hex');
                var detail =item[0]['detail']; 
                var fromType = detail['fromType'];
                fromType['fromType'] = fromType['fromType'].split('搜索词:')[1];
                fromType['fromType'] = fromType['fromType'].replace(')','');
                fromType['accessPage'] = detail['accessPage'];
            }catch(e){
                console.info('sendItems Error',e);
                continue;
            }
            if(urlCache[md5Item]){
                continue;
            }
            if(parseInt(Math.random()*10000) == 1000){
                urlCache = {};
            }
            urlCache[md5Item]=true;
            Actions.sendItem(fromType);
        }
    },
    sendItem: function(fromType){
        var options = {
            method: 'POST',
            timeout: 10*1000,
            data: fromType
        }
        urllib.request(config.trackingHost, options, function(err, data, res){
            console.info('sendItem keyword:',fromType);
        })
    },
    getCASCode: function(code){
        client.click('#change_cas');
        setTimeout(function(){
            var top = 0;
            var left = 0;
            client.getCssProperty('.dialog-container','top').then(function(topvalue) {
                top = topvalue['parsed']['value'];
            }).getCssProperty('.dialog-container','left').then(function(topvalue) {
                left = topvalue['parsed']['value'];
            })
            .saveScreenshot('./snapshot.png')
            .getTitle().then(function(title) {
                console.info('top',top);
                console.info('left',left);
                left += 190;
                top += 210;
                gm('./snapshot.png')
                .crop(76,40, left,top)
                .write('./snapshot1.png', function (err) {
                    processImg('./snapshot1.png', './snapshot_temp.png')
                    .then(recognizer)
                    .then(text => {
                        Actions.callback(null,text);
                        // console.log(`识别结果:${text}`);
                    })
                    .catch((err)=> {
                        console.error(`识别失败:${err}`);
                    });
                })
            })
        },1500)
    }
}

/**
 * 处理图片为阈值图片
 * @param imgPath
 * @param newPath
 * @param [thresholdVal=55] 默认阈值
 * @returns {Promise}
 */
function processImg (imgPath, newPath, thresholdVal) {
    return new Promise((resolve, reject) => {
        gm(imgPath)
            // .threshold(thresholdVal || 55)
            .write(newPath, (err)=> {
                if (err) return reject(err);

                resolve(newPath);
            });
    });
}

/**
 * 识别图片
 * @param imgPath
 * @param options tesseract options
 * @returns {Promise}
 */
function recognizer (imgPath, options) {
    // console.info('options',options);
    options = Object.assign({psm: 7}, options);

    return new Promise((resolve, reject) => {
        tesseract
            .process(imgPath, options, (err, text) => {
                if (err) return reject(err);
                resolve(text.replace(/[\r\n\s]/gm, ''));
            });
    });
}
module.exports = Actions;